<template>
  <div id="register">
    <div class="login-title-logo">
      <img class="logo-header" src="static/logoh.png" alt="">
      <p class="title-name">BestProperty</p>
      <p class="balck"></p>
    </div>
    <div class="demo-ruleForm login-container">
      <div class="lang-img" @click="changeLang">
        <img :src="langImage" alt="">
      </div>
      <h3 class="title">{{$t('m.Register')}}</h3>
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="Google/Facebook" name="first">
          <el-form>
            <div style="margin-top:20px;">
              <el-form-item>
                <el-button class="facebook-btn" style="width:100%;" :loading="loading" @click="faceBookRegister"><i
                  :style="{backgroundImage: 'url(' + require('../../static/fb-icon.png') + ')'}"
                  class="facebook-icon"></i>Login with Facebook
                </el-button>
              </el-form-item>
              <el-form-item style="margin-bottom:0;">
                <div id="googleBtnRegister" class="google-btn"></div>
              </el-form-item>
              <el-form-item prop="type" class="terms-condition">
                <el-checkbox :checked="checked" disabled style="text-align:center;">I accept
                  <router-link to="/terms" style="color:rgb(153, 153, 153);">Terms & Conditions</router-link>
                </el-checkbox>
              </el-form-item>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="Email" name="second">
          <el-form :model="registerWithEmail" :rules="rulesWithEmail" ref="registerWithEmail" label-position="left"
                   class="demo-ruleForm">
            <el-form-item prop="email" :label="$t('m.Email')" style="margin-bottom:5px;">
              <el-input v-model="registerWithEmail.email" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('m.Password')" prop="password">
              <el-input type="password" v-model="registerWithEmail.password" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0;">
              <el-button type="warning" style="width:100%;" :loading="loading"
                         @click="submitEmailForm('registerWithEmail')">{{$t('m.SendVerificationtomyemail')}}
              </el-button>
            </el-form-item>
            <el-form-item prop="type" class="terms-condition">
              <el-checkbox-group v-model="registerWithEmail.type">
                <el-checkbox :checked="checkedEmail" style="text-align:center;">I accept
                  <router-link to="/terms" style="color:rgb(153, 153, 153);">Terms & Conditions</router-link>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <el-dialog
            :title="$t('m.EmailConfirmation')"
            :visible.sync="dialogVisible"
            :before-close="goToLogin"
            width="25%">
            <span>{{$t('m.Checkyouremailinbox')}}</span>
            <div class="btootm" style="text-align: center; padding-top: 20px">
              <el-button type="primary" @click="goToLogin">{{$t('m.Close')}}</el-button>
            </div>
          </el-dialog>
        </el-tab-pane>
        <!--隐蔽手机号注册-->
        <!--<el-tab-pane :label="$t('m.Phone')" name="third">-->
          <!--<el-form :model="register" :rules="rules" ref="register" label-position="left" class="demo-ruleForm">-->
            <!--<el-form-item prop="userName"  :label="$t('m.DisplayName')" style="margin-bottom:0;">-->
              <!--<el-input v-model.userName="register.userName" auto-complete="off" ></el-input>-->
            <!--</el-form-item>-->
            <!--&lt;!&ndash;注册时隐藏城市信息&ndash;&gt;-->
            <!--&lt;!&ndash;<el-form-item label="Region" prop="regionId" style="margin-bottom:0;">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-select v-model="register.regionId" placeholder="" @change="getTownships($event)">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-option v-for="rg in regions" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>&ndash;&gt;-->
            <!--&lt;!&ndash;</el-select>&ndash;&gt;-->
            <!--&lt;!&ndash;</el-form-item>&ndash;&gt;-->
            <!--&lt;!&ndash;<el-form-item label="Township" prop="townshipId" style="margin-bottom:0;">&ndash;&gt;-->
            <!--&lt;!&ndash;<el-select v-model="register.townshipId" placeholder="" >&ndash;&gt;-->
            <!--&lt;!&ndash;<el-option v-for="ts in townships" :key="ts.value" :label="ts.text" :value="ts.value"></el-option>&ndash;&gt;-->
            <!--&lt;!&ndash;</el-select>&ndash;&gt;-->
            <!--&lt;!&ndash;</el-form-item>&ndash;&gt;-->
            <!--<el-form-item prop="phone" :label="$t('m.Phone')" style="margin-bottom:0;">-->
              <!--<el-input v-model="register.phone" auto-complete="off"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="password" :label="$t('m.Password')" >-->
              <!--<el-input type="password" v-model="register.password" auto-complete="off"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item style="margin-bottom:0;">-->
              <!--<el-button class="smsBtn" :disabled="sendMsgDisabled" @click="submitSms('register')">-->
                <!--<span v-if="sendMsgDisabled">{{'Resend SMS password to my phone ' + time + 's'}}</span>-->
                <!--<span v-else>{{$t('m.SendSMSpasswordtomyphone')}}</span>-->
              <!--</el-button>-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="sms" :label="$t('m.SMSPassword')">-->
              <!--<el-input v-model="register.sms" :maxlength="4" auto-complete="off"></el-input>-->
            <!--</el-form-item>-->
            <!--<el-form-item style="margin-bottom:0;">-->
              <!--<el-button type="warning" style="width:100%;" :loading="loading" @click="submitForm('register')">-->
                <!--{{$t('m.Register')}}-->
              <!--</el-button>-->
            <!--</el-form-item>-->
            <!--<el-form-item prop="type" class="terms-condition">-->
              <!--<el-checkbox-group v-model="register.type">-->
                <!--<el-checkbox :checked="checked" style="text-align:center;">I accept-->
                  <!--<router-link to="/terms" style="color:rgb(153, 153, 153);">Terms & Conditions</router-link>-->
                <!--</el-checkbox>-->
              <!--</el-checkbox-group>-->
            <!--</el-form-item>-->
          <!--</el-form>-->
        <!--</el-tab-pane>-->
        <router-link to="/login" class="index-page-a">{{$t('m.AlreadyhaveaccountLogin')}}</router-link>
      </el-tabs>
    </div>
    <div style="text-align:center;">
      <p>Customer support</p>
      <p>09967611168 | 09951203008</p>
    </div>
  </div>
</template>

<script>
  import regions from '@/json/region'
  import townships from '@/json/township'
  import { registerUser, sendSmsUser, registerUserWithEmail, registerWithGoogle, registerWithFaceBook } from '@/api/mgc_api'
  import Qs from 'qs'

  export default {
    name: 'Register',
    data () {
      return {
        register: {
          // userName: '',
          phone: '',
          sms: '',
          type: [],
          // regionId: '',
          // townshipId: '',
          password: ''
        },
        registerWithEmail: {
          email: '',
          password: '',
          type: []
        },
        activeName: 'first',
        regions: regions,
        townships: [],
        checked: true,
        checkedEmail: true,
        send: 'Send SMS',
        time: 60, // 发送验证码倒计时
        sendMsgDisabled: false,
        loading: false,
        dialogVisible: false,
        rules: {
          userName: [
            {required: true, message: 'your name is null'}
          ],
          regionId: [
            {required: true, type: 'number', message: 'please select region', trigger: 'change'}
          ],
          townshipId: [
            {required: true, type: 'number', message: 'please select Township', trigger: 'change'}
          ],
          phone: [
            {required: true, message: 'phone is null'}
          ],
          sms: [
            {required: true, message: 'sms is null'}
          ],
          type: [
            {type: 'array', required: true, message: '"Terms & Conditions" mustbe checked', trigger: 'change'}
          ],
          password: [{
            validator: (rule, value, callback) => {
              if(value != ''){
                if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                  callback(new Error('At least 8 or more characters and at least 1 number.'))
                } else {
                  callback()
                }
              }
            }, trigger: 'blur',
          }],
        },
        rulesWithEmail: {
          email: [
            {required: true, message: 'Please enter the mailbox address', trigger: 'blur'},
            {type: 'email', message: 'Please enter the correct mailbox address', trigger: 'blur'}
          ],
          // password: [
          //   {required: true, message: 'password is null'}
          //   ^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$
          // ],
          password: [{
            validator: (rule, value, callback) => {
              if (/^(?=.*?[0-9]).{8,}$/.test(value) == false) {
                callback(new Error('At least 8 or more characters and at least 1 number'))
              } else {
                callback()
              }
            }, trigger: 'blur'
          },
            {required: true, message: 'Please enter password', trigger: 'blur'}],
          type: [
            {type: 'array', required: true, message: '"Terms & Conditions" mustbe checked', trigger: 'change'}
          ],
        },
        langImage: '../../static/usLang.png',
      }
    },
    methods: {
      // 切换语言
      changeLang () {
        if(this.$i18n.locale == 'MM'){
          this.$i18n.locale = 'US'
          this.lang = 'ျမန္မာ'
          this.$store.commit('updateLang', 'US')
          this.langImage = '../../static/myanmar.png'
        }else if(this.$i18n.locale == 'US'){
          this.$i18n.locale = 'MM'
          this.lang='English'
          this.$store.commit('updateLang', 'MM')
          this.langImage = '../../static/usLang.png'
        }
      },
      getTownships (regionId) {
        let town = []
        this.townships = []
        this.register.townshipId = ''
        for (var t of townships) {
          if (regionId === t.regionId) {
            town.push({value: t.value, text: t.text})
          }
        }
        this.townships = town
      },
      timeGo: function () {
        var self = this
        self.sendMsgDisabled = true
        var timeCount = setInterval(function () {
          if ((self.time--) <= 0) {
            self.time = 60
            self.sendMsgDisabled = false
            window.clearInterval(timeCount)
          }
        }, 1000)
      },
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 1500,
          type: 'error'
        })
      },
      // 去掉空格
      trim (str, isGlobal) {
        var result
        result = str.replace(/(^\s+)|(\s+$)/g, '')
        if (isGlobal.toLowerCase() === 'g') {
          result = result.replace(/\s/g, '')
        }
        return result
      },
      // Register send sms
      submitSms: function (formName) {
        var self = this
        // && this.register.userName && this.register.regionId && this.register.townshipId 注册时隐藏城市信息
        // && /^(?=.*?[0-9]).{8,}$/.test(this.register.password)
        if (this.register.password != '') {
          if (!/^(?=.*?[0-9]).{8,}$/.test(this.register.password)) {
            this.messageToastErr('error submit!!')
            return false
          }
        }
        if ( this.register.userName && this.register.phone ) {
          let phoneNumber = this.trim(this.register.phone, 'g')
          phoneNumber = phoneNumber.substring(1, phoneNumber.length)
          this.timeGo()
          let data = {
            'phoneNumber': phoneNumber,
            'zone': '+95'
          }
          let params = Qs.stringify(data)
          sendSmsUser(params)
            .then(function (res) {
              if (res.data) {
                var data = res.data
                if (data.errorID === 0) {
                  console.log(data)
                } else {
                  console.log(data)
                  self.showToast(data.errorID)
                }
              }
            })
            .catch(function (error) {
              console.log(error)
              self.messageToastErr('error,please try again leter')
            })
        } else {
          console.log('error submit!!')
          self.messageToastErr('error submit!!')
          return false
        }
      },
      // Register submit Form
      submitForm: function (formName) {
        var self = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let phoneNumber = this.trim(this.register.phone, 'g')
            let data = {
              'name': self.register.userName,
              'phoneNumber': phoneNumber,
              'zone': '+95',
              'code': self.register.sms,
              // 'regionId': self.register.regionId,
              // 'townshipId': self.register.townshipId,
              'password': self.register.password
            }
            let params = Qs.stringify(data)
            self.loading = true
            registerUser(params)
              .then((res) => {
                if (res.data) {
                  var data = res.data
                  if (data.errorID === 0) {
                    localStorage.setItem('username', data.object.name)
                    localStorage.setItem('developerId', data.object.id)
                    localStorage.setItem('account', data.object.account)
                    self.$store.commit('updateUserName', data.object.name)
                    self.$store.commit('updateDeveloperId', data.object.id)
                    self.$store.commit('updateAccount', data.object.account)
                    self.loading = false
                    self.$router.push('/mainPage')
                  } else {
                    console.log(data)
                    self.loading = false
                    self.showToast(data.errorID)
                  }
                }
              })
              .catch(function (error) {
                console.log(error)
                self.loading = false
                self.messageToastErr('error,please try again leter')
              })
          } else {
            self.messageToastErr('error submit!!')
            return false
          }
        })
      },
      //邮箱注册
      submitEmailForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              'accountEmail': this.registerWithEmail.email,
              'password': this.registerWithEmail.password
            }
            let params = Qs.stringify(data)
            this.loading = true
            registerUserWithEmail(params)
              .then((res) => {
                if (res.data) {
                  var data = res.data
                  if (data.errorID === 0) {
                    this.showToast(data.errorID)
                    this.$refs[formName].resetFields()
                    this.loading = false
                    setTimeout(() => {
                      this.dialogVisible = true
                    }, 1200)
                  } else {
                    console.log(data)
                    this.loading = false
                    this.showToast(data.errorID)
                  }
                }
              })
              .catch((error) => {
                console.log(error)
                this.loading = false
                this.messageToastErr('error,please try again leter')
              })
          } else {
            this.messageToastErr('error submit!!')
            return false
          }
        })
      },
      // 谷歌登注册成功后回调函数
      onSuccessRegister (googleUser) {
        var googleId = googleUser.getBasicProfile().getId()
        var name = googleUser.getBasicProfile().getName()
        var email = googleUser.getBasicProfile().getEmail()
        let data = {
          'googleId': googleId,
          'googleName': name,
          'googleEmail': email
        }
        let params = Qs.stringify(data)
        registerWithGoogle(params).then((res) => {
          if (res.data) {
            let data = res.data
            if (data.errorID === 0) {
              // this.signOutGoogle()
              this.showToast(data.errorID)
              var auth2 = window.gapi.auth2.getAuthInstance()
              auth2.signOut().then(() => {
                this.$router.push('/mainPage')
                console.log('User signed out.')
              })
              return false
            } else {
              console.log(data.errorID)
              this.showToast(data.errorID)
              return false
            }
          }
        }).catch((error) => {
          console.log(error)
          this.messageToastErr('error,please try again leter')
          return false
        })
      },
      // 谷歌登录失败回调函数
      onFailureRegister (e) {
        console.log('Google login error~')
        this.messageToastErr('error,please try again leter')
        return false
      },
      //登錄成功后退出谷歌登錄狀態
      signOutGoogle () {
        var auth2 = window.gapi.auth2.getAuthInstance()
        auth2.signOut().then(function () {
          console.log('User signed out.')
        })
      },
      //初始化谷歌登录按钮
      renderButton () {
        window.gapi.signin2.render('googleBtnRegister', {
          'scope': 'profile email',
          'width': 380,
          'height': 40,
          'longtitle': true,
          'theme': 'dark',
          'onsuccess': this.onSuccessRegister,
          'onfailure': this.onFailureRegister
        })
      },
      // 調用FaceBook登錄按鈕
      faceBookRegister () {
        window.FB.login((response) => {
          this.statusChangeCallback(response)
        }, {scope: 'email'})
      },
      statusChangeCallback (response) {
        if (response.status === 'connected') {
          FB.api('/me?fields=name,email', (response) => { // /me为API指定的调用方法，用于获取登陆用户相关信息
            if (response.email != null) {
              this.registerWithFaceBookLast(response)
            } else {
              this.messageToastErr('error,please try again leter')
            }
          })
        }
      },
      //facebook登录成功后回调--登录
      registerWithFaceBookLast (response) {
        if (response) {
          var facebookId = response.id
          var name = response.name
          var email = response.email
          let data = {
            'facebookId': facebookId,
            'facebookName': name,
            'facebookEmail': email
          }
          let params = Qs.stringify(data)
          registerWithFaceBook(params).then((res) => {
            if (res.data) {
              let data = res.data
              if (data.errorID === 0) {
                this.showToast(data.errorID)
                window.FB.logout(function (response) {
                  // Person is now logged out
                  this.$router.push('/mainPage')
                  console.log('feacbook logged out')
                })
                return false
              } else {
                console.log(data.errorID)
                this.showToast(data.errorID)
                return false
              }
            }
          }).catch((error) => {
            console.log(error)
            this.messageToastErr('error,please try again leter')
            return false
          })
        }
      },
      // 关闭dialog 跳转到login
      goToLogin(){
        this.dialogVisible = false;
        this.$router.push('/login')
      }
    },
    mounted () {
      this.renderButton()
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .login-container {
    /*box-shadow: 0 0px 8px 0 rgba(0, 0, 0, 0.06), 0 1px 0px 0 rgba(0, 0, 0, 0.02);*/
    -webkit-border-radius: 5px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    background-clip: padding-box;
    /* margin: 180px auto; */
    margin: 0 auto;
    width: 380px;
    padding: 35px 35px 25px 35px;
    background: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    margin-bottom: 50px;
    position: relative;
  }

  .login-title-logo {
    width: 100%;
    text-align: center;
    margin-top: 10px;
  }

  .login-container .title {
    margin: 0px auto 20px auto;
    padding: 10px 0;
    text-align: center;
    color: #505458;
  }

  .login-container .remember {
    margin: 0px 0px 35px 0px;
  }

  .smsBtn {
    width: 100%;
    padding: 12px 5px;
  }

  .login-title-logo .logo-header {
    width: 100px;
  }

  .login-title-logo .title-name {
    margin: 0;
    font-size: 18px;
    color: rgb(255, 153, 0);
  }

  .login-title-logo .balck {
    margin: 0.4em 0 2em 0;
  }

  .login-container .el-tabs__item:hover, .login-container .el-tabs__item.is-active, .login-container .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #FF9900;
  }

  .login-container .el-checkbox__input.is-focus .el-checkbox__inner, .login-container .el-checkbox__inner:hover {
    border-color: #FF9900;
  }

  .login-container .el-button--warning, .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #FF9900;
    border-color: #FF9900;
  }

  #register .index-page-a {
    text-decoration: none;
    color: #FF9900;
    text-align: center;
    display: block;
  }

  .login-container .el-select {
    width: 100%;
  }

  .login-container .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: none;
  }

  .login-container .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    border-bottom-color: #FF9900;
  }

  .login-container .el-tabs--card > .el-tabs__header .el-tabs__item {
    border-left: none;
  }

  .login-container .el-tabs__item {
    padding: 0;
    flex: 1;
    text-align: center;
  }

  .login-container .el-tabs__nav {
    width: 100%;
    display: flex;
  }

  .login-container .el-tabs__active-bar {
    background-color: #FF9900;
  }

  .terms-condition {
    text-align: left;
    height: 30px;
    line-height: 30px;
  }

  .terms-condition .el-form-item__content {
    height: 30px;
  }

  #register .google-btn {
    width: 100%;
    height: 40px;
  }

  #register .google-btn .abcRioButtonBlue .abcRioButtonIcon {
    background-color: transparent;
    display: none;
  }

  #register .google-btn .abcRioButtonBlue {
    background-color: #fff;
    box-shadow: none;
    border-radius: 5px;
    border: 1px solid #888;
    color: #444;
  }

  #register .google-btn .abcRioButtonBlue .abcRioButtonContentWrapper {
    border: none;
  }

  #register .google-btn .abcRioButtonBlue:hover {
    background-color: #fff;
    box-shadow: none;
  }

  #register .login-container .facebook-btn {
    background-color: #3b5998 !important;
    border: 1px solid #3b5998 !important;
    color: #fff !important;
  }

  #register .login-container .facebook-btn:hover {
    background-color: #5477c0 !important;
    border: 1px solid #5477c0 !important;
    color: #fff !important;
  }

  #register .login-container .facebook-btn span {
    display: none;
  }

  #register .login-container .facebook-btn:before {
    content: 'Register with Facebook';
    top: 0;
    left: 0;
  }

  #register .login-container .facebook-icon {
    position: absolute;
    left: 0;
    top: 0;
    width: 18px;
    height: 18px;
    margin: 10px;
    background-size: 100% 100%;
  }

  #register .login-container .abcRioButtonContents:before {
    content: 'Register with Google';
    top: 0;
    left: 0;
  }

  #register .login-container .facebook-btn span {
    margin-left: 30px;
  }

  #register .login-container .abcRioButtonContents {
    /*margin-right:40px;*/
  }

  #register .login-container .abcRioButtonContents span {
    display: none
  }
  .lang-img {
    position: absolute;
    cursor: pointer;
    padding: 5px;
    right: 15px;
    top: 15px;
  }
</style>
